﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public static string SelectedTitleID, SelectedGameName, xmlLocation, test1;
        public static int test2, SkippedGames, DownloadedTUCount;
        int GameCount;
        public static bool Finished, getnames, updateComplete, LogChanged;


        public static ListViewGroup GamesList = new ListViewGroup();
        public static ListBox LogList = new ListBox();

        public Form1()
        {
            InitializeComponent();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            backgroundWorker1.WorkerSupportsCancellation = true;
            backgroundWorker1.RunWorkerAsync();

            LogChanged = false;
            if (Directory.Exists("cache") != true)
            {
                Directory.CreateDirectory("cache");
            }

            LoglistBox.Items.Add("TUDifier has started");
            LoglistBox.Items.Add("   Scuba156 (Xbox1Crew, XeLove)");
            LoglistBox.Items.Add("   Select 'open Content.xml' to start");

            getnames = true;
            updateComplete = false;

        }

        private void openContentxmlToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog fDialog = new OpenFileDialog();

                fDialog.CheckFileExists = true;
                fDialog.Filter = ".xml|*.xml|All Files|*.*";
                fDialog.FileName = "Content.xml";
                if (fDialog.ShowDialog() == DialogResult.OK)
                {
                    xmlLocation = fDialog.FileName;

                    GameslistView.Items.Clear();
                    GamesList.Items.Clear();
                    XMLStuff.CheckXMLIntegrity();
                    XMLStuff.InitialXMLRead(false);

                    GameslistView.Columns[2].Text = "Media ID";

                    GameslistView.Items.AddRange(GamesList.Items);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not open file" + Environment.NewLine + Environment.NewLine + ex.Message, "An Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
                GameslistView.Items.Clear();
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void LogList_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.LoglistBox.Items.AddRange(LogList.Items);
        }

        private void getTusForSelectedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int i = 0;
            int count = 1;
            DownloadedTUCount = 0;
            SkippedGames = 0;
            //do
            //{
            //    System.Threading.Thread.Sleep(100);
            //} while (backgroundWorker1.IsBusy == true);

            backgroundWorker1.CancelAsync();

            if (GameslistView.Items.Count >= 0 && GameslistView.SelectedItems.Count != 0)
            {
                GameCount = GameslistView.SelectedItems.Count;

                Progress ProgressForm = new Progress();

                ProgressForm.progressBar1.Maximum = GameCount;
                ProgressForm.progressBar1.Value = 0;

                ProgressForm.TotalGamesLabel.Text = null;
                ProgressForm.GameNameLabel.Text = null;
                ProgressForm.webaddressLabel.Text = null;
                ProgressForm.GameNumberLabel.Text = null;
                ProgressForm.Show();
                Finished = false;
                do
                {
                    if (GameslistView.Items[i].Selected != false)
                    {
                        Form1.SelectedTitleID = GameslistView.Items[i].SubItems[1].Text;
                        SelectedGameName = GameslistView.Items[i].SubItems[0].Text;

                        string webPath = "http://marketplace.xboxmodder.com.nyud.net/dlc/" + Form1.SelectedTitleID + "/000B0000/";
                        string DestPath = "TU_Temp_List";

                        ProgressForm.TotalGamesLabel.Text = "of " + GameCount;
                        ProgressForm.GameNameLabel.Text = SelectedGameName;
                        ProgressForm.webaddressLabel.Text = webPath;
                        ProgressForm.GameNumberLabel.Text = count.ToString();
                        ProgressForm.progressBar1.Value = count;
                        ProgressForm.Refresh();
                        ProgressForm.Focus();
                        if (File.Exists(DestPath))
                        {
                            File.Delete(DestPath);
                        }
                        if (NetStuff.DownloadFile(webPath, DestPath, false) == true)
                        {
                            String Filea;
                            StreamReader oRead;
                            oRead = File.OpenText("TU_Temp_List");

                            oRead.BaseStream.Seek(55, SeekOrigin.Begin);
                            Filea = oRead.ReadToEnd();
                            oRead.Close();

                            File.WriteAllText("TU_TempList.xml", Filea);

                            XmlDocument xDoc = new XmlDocument();
                            xDoc.Load("TU_TempList.xml");

                            XmlNodeList name = xDoc.GetElementsByTagName("li");

                            for (int index = 1; index <= name.Count - 1; index++)
                            {
                                webPath = "http://marketplace.xboxmodder.com.nyud.net/dlc/" + SelectedTitleID + "/000B0000/" + name[index].InnerText.Remove(0, 1);
                                if (File.Exists("cache/" + name[index].InnerText.Remove(0, 1)) != true)
                                {
                                    DestPath = "cache/" + name[index].InnerText.Remove(0, 1);

                                    ProgressForm.webaddressLabel.Text = webPath;
                                    ProgressForm.Refresh();
                                    ProgressForm.Focus();
                                    NetStuff.DownloadFile(webPath, DestPath, true);
                                    DownloadedTUCount++;
                                }
                                else
                                {
                                    Form1.ErrorLogWrite("TU already exists", "cache/" + name[index].InnerText.Remove(0, 1));
                                    LoglistBox.Items.Add(LogList.Items[0]);
                                    LogList.SelectedIndex = LogList.Items.Count - 1;
                                    SkippedGames++;
                                    LoglistBox.SelectedIndex = LoglistBox.Items.Count - 1;
                                    LoglistBox.SelectedIndex = -1;
                                    //LoglistBox.Items.Add("TU already exists ::" + " cache/" + name[index].InnerText.Remove(0, 1));
                                }

                            }
                            
                            if (File.Exists("TU_Temp_List"))
                            {
                                File.Delete("TU_Temp_List");
                            }
                            if(File.Exists("TU_TempList.xml"))
                            {
                                File.Delete("TU_TempList.xml");
                            }
                            
                        }
                        count++;
                    }
                    i++;
                } while (i != GameslistView.Items.Count);

                Form1.Finished = true;
                ProgressForm.Close();

                Form1.WriteMessage("   Total Games = " + GameslistView.SelectedItems.Count + " :: Total TUDified = " + DownloadedTUCount.ToString() + " :: Total Skipped = " + SkippedGames.ToString());
                LoglistBox.Items.Add(LogList.Items[0]);
            }
            else
            {
                MessageBox.Show("No Games were selected.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            }
        }

        private void getAllTusOnServerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String WebPath = "http://marketplace.xboxmodder.com.nyud.net/updates.xml";
            if (NetStuff.DownloadFile(WebPath, "TU_DB.xml", false))
            {

            XmlDocument TUXML = new XmlDocument();

            if(File.Exists("TU_DB.xml"))
            {
                TUXML.Load("TU_DB.xml");

                XmlNodeList FolderPath = TUXML.GetElementsByTagName("folder");
                XmlNodeList FilePath = TUXML.GetElementsByTagName("filename");

                //for(int indexCount = 0, index = (FolderPath.Count - 1))
                //{

                //}

            }
            }
        }

        private void openFSD2AlphaFsd2contentxmlToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog fDialog = new OpenFileDialog();

                fDialog.CheckFileExists = true;
                fDialog.Filter = ".xml|*.xml|All Files|*.*";
                fDialog.FileName = "fsd2content.xml";
                if (fDialog.ShowDialog() == DialogResult.OK)
                {
                    xmlLocation = fDialog.FileName;

                    GameslistView.Items.Clear();
                    GamesList.Items.Clear();
                    //XMLStuff.CheckXMLIntegrity(); shouldnt be needed
                    XMLStuff.InitialXMLRead(true);

                    GameslistView.Items.AddRange(GamesList.Items);
                    GameslistView.Columns[2].Text = "Game Type";
                    GameslistView.Refresh();
                    if (getnames = true)
                    {
                        System.Threading.Thread.Sleep(1000);
                        GameNamebackgroundWorker.RunWorkerAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not open file" + Environment.NewLine + Environment.NewLine + ex.Message, "An Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
                GameslistView.Items.Clear();
            }
        }

        private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int count = GameslistView.Items.Count - 1;
            for (int item = 0; item <= count; item++ )
            {
                GameslistView.Items[item].Selected = true;
            }
        }

        private void invertSelectionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int count = GameslistView.Items.Count - 1;
            for (int item = 0; item <= count; item++)
            {
                if (GameslistView.Items[item].Selected == true)
                {
                    GameslistView.Items[item].Selected = false;
                }
                else
                {
                    GameslistView.Items[item].Selected = true;
                }
            }
        }

        private void GameslistView_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyCode == Keys.Control) && (e.KeyCode == Keys.A))
            {
                selectAllToolStripMenuItem_Click(sender, e);
            }
        }

        private void getGameNamesfsd2OnlyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            getnames = getGameNamesfsd2OnlyToolStripMenuItem.Checked;
            
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            if (NetStuff.DownloadFile("http://marketplace.xboxmodder.com.nyud.net/titleupdates.xml", "TUDataBase.xml", false))
        {
            updateComplete = true;
        }
        else
        {
            updateComplete = false;
        }

        
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (updateComplete == true)
            {
                LoglistBox.Items.Add("   TUDataBase.xml was updated successfully");
            }
            else
            {
                LoglistBox.Items.Add("   TUDataBase.xml was not updated");
            }
        }

        private void GameNamebackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                GameNamebackgroundWorker.WorkerReportsProgress = true;
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load("GameDataBase.xml");

                XmlNodeList Game = xDoc.GetElementsByTagName("Game");
                //XmlNodeList TitleIDxml = xDoc.GetElementsByTagName("TitleID");
                //XmlNodeList GameNamexml = xDoc.GetElementsByTagName("GameName");
                int Count = Game.Count - 1;
                int GamesCount = 0;
                string TitleID;
                int test = GamesList.Items.Count - 1;
                for (int i = 0; i <= test; i++)
                {
                    bool Found = false;
                    for (int index = 0; index <= Count; index++)
                    {

                        TitleID = GamesList.Items[i].SubItems[1].Text;
                        string blah = Game.Item(index).ChildNodes.Item(1).InnerText.ToUpper();
                        if (TitleID.CompareTo(blah) == 0)  //(TitleID == blah) ;//Game.Item(index).ChildNodes.Item(0).InnerText.ToUpper()) ; //TitleIDxml.Item(index).InnerText.ToUpper());
                        {
                            GamesCount++;
                            test2 = GamesCount;
                            test1 = Game.Item(index).ChildNodes.Item(0).InnerText.ToString();
                            Found = true;
                            //this.GamesListView.Items[GamesCount].SubItems[0].Text = Game.Item(index).ChildNodes.Item(0).InnerText.ToString(); //GameNamexml.Item(index).ChildNodes.Item(index).InnerText;
                            break;
                            //GameNamebackgroundWorker.ReportProgress(+1);
                        }
                    }
                    if (Found == true)
                    {
                        GameNamebackgroundWorker.ReportProgress(i);
                        System.Threading.Thread.Sleep(20);
                    }
                    else
                    {
                        test1 = "";
                        test2 = 0;
                        //test
                    }
                }

                //this.LoglistBox.Items.Add("Not Found");
                //return "Not found";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void GameNamebackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.LoglistBox.Items.Add("   " + xmlLocation.ToString() + " loaded successfully");
        }

        private void GameNamebackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.GameslistView.Items[e.ProgressPercentage].SubItems[0].Text = test1;
        }


        public static void ErrorLogWrite(string ErrorString, string Item)
        {
            LogList.Items.Clear();
            Form1.LogList.Items.Add("   " + ErrorString + "::" + Item);
            LogList.SelectedIndex = Form1.LogList.Items.Count - 1;
            Form1.LogList.SelectedIndex = -1;
            Form1.LogList.Refresh();
            Form1.LogChanged = true;
        }

        public static void WriteMessage(string Message)
        {
            LogList.Items.Clear();

            Form1.LogList.Items.Add("   " + Message);
            Form1.LogList.SelectedIndex = Form1.LogList.Items.Count - 1;
            Form1.LogList.SelectedIndex = -1;
            Form1.LogList.Refresh();
        }
    }
}
